<?php   // $Id: fact_creer_suite.php 347 2012-05-07 09:11:55Z pcoustillas $ ?>
<?php   
/*Copyright (C) 2003-2004 Guy Hendrickx
Licensed under the terms of the GNU  General Public License:http://www.opensource.org/licenses/gpl-license.php
File Authors:Guy Hendrickx
Modification : Pierre Coustillas*/

require_once("include/verif.php");
require_once("include/config/common.php");
require_once("include/config/var.php");
require_once("include/language/$lang.php");
require_once("include/utils.php");


$acompte=isset($_POST['acompte'])?$_POST['acompte']:"";
$date_deb=isset($_POST['date_deb'])?$_POST['date_deb']:"";
$date_fin=isset($_POST['date_fin'])?$_POST['date_fin']:"";
$date_fact=isset($_POST['date_fact'])?$_POST['date_fact']:"";
$client=isset($_POST['num_client'])?$_POST['num_client']:"";
$reference=isset($_POST['reference'])?$_POST['reference']:"";
$coment=isset($_POST['coment'])?$_POST['coment']:"";

$debut = date_to_sql($date_deb);
$fin = date_to_sql($date_fin);
$date_fact = date_to_sql($date_fact);

if($client=='0' || $date_deb==''|| $date_fin=='' || $date_fact=='' )
{
	$message= "<h1>$lang_oubli_champ</h1>";
	header("Location: fact_creer.php?message=Valeur manquante");
	exit;
}

//on recherche le numero de la facture à crée
$sql = "SELECT MAX(num) As Maxi FROM ${tblpref}facture";
$result = mysql_query($sql) or die('Erreur');
$num_fact = mysql_result($result, 0);
$num_fact = $num_fact + 1 ;

// on met à jour les bon de commandes qui ne sont pas facturées
$sql = "UPDATE ${tblpref}bon_comm SET num_facture=$num_fact
		 WHERE ${tblpref}bon_comm.client_num = '$client' 
		 AND ${tblpref}bon_comm.date >= '$debut' 
		 AND ${tblpref}bon_comm.date <= '$fin'
		 AND num_facture = 0";
mysql_query($sql) OR die("Erreur mise à jour des bons de commandes<br/>$sql<br/>" . mysql_error());


$sql = " SELECT SUM(tot_htva), SUM(tot_tva) 
		FROM ${tblpref}bon_comm 
		 WHERE ${tblpref}bon_comm.client_num = '$client' 
		 AND ${tblpref}bon_comm.date >= '$debut' 
		 AND ${tblpref}bon_comm.date <= '$fin'
		 AND num_facture = $num_fact";

$req = mysql_query($sql) or die("Erreur SQL !<br/>$sql<br/>" . mysql_error());
$data = mysql_fetch_array($req);
$total_htva = $data['SUM(tot_htva)'];
$total_tva = $data['SUM(tot_tva)'];
$total_ttc = $total_htva + $total_tva;


//créer la facture
$sql1 = "INSERT INTO ${tblpref}facture(num,acompte,reference, coment, client, date_fact, total_fact_h, total_fact_ttc)
	 VALUES ('$num_fact','$acompte','$reference', '$coment', '$client', '$date_fact', '$total_htva', '$total_ttc')";
mysql_query($sql1) or die("Erreur SQL1 !<br/>$sql1<br/>" . mysql_error());


header("Location: fact_edit.php?num_fact=$num_fact");
?>
